package perceptronMathieu.function;

import perceptronMathieu.Perceptron;

public class XOR implements IFunction
{
	private final Perceptron	perceptron;

	public XOR()
	{
		this.perceptron = new Perceptron(2, 1, 3, 1);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see app.Function#getDimension()
	 */
	public int getDimension()
	{
		return perceptron.getLinksCount();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see app.Function#fitness(double[])
	 */
	public double fitness(double linkValues[])
	{
		double fitness = 0.0;
		perceptron.setLinks(linkValues);

		fitness += delta(false, false);
		fitness += delta(false, true);
		fitness += delta(true, false);
		fitness += delta(true, true);

		return fitness;
	}

	public double delta(boolean x, boolean y)
	{
		perceptron.setInput(0, (x ? 1 : 0));
		perceptron.setInput(1, (y ? 1 : 0));

		perceptron.activate();
		double delta = Math.abs(perceptron.getOutput(0) - ((x ^ y) ? 1 : 0));

		return delta * delta;
	}

	public boolean test(boolean x, boolean y)
	{
		perceptron.setInput(0, x ? 1 : 0);
		perceptron.setInput(1, y ? 1 : 0);
		perceptron.activate();

		return ((perceptron.getOutput(0) < 0.5) ? false : true) == (x ^ y);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see app.Function#toString()
	 */
	public String toString()
	{
		return perceptron.toString();
	}
}
